<template>
	<div class="app-container" style="padding:20px">
			<el-card>
				<div class="flex_hcneter_bet">
					<div class="flex_hcneter">
						<div class="wordBreak">文件名称</div>
						<el-input class="margin_lr" v-model="info.name" placeholder="请输入文件名称"></el-input>
						<el-input class="margin_lr" v-model="info.code" placeholder="请输入文件编码"></el-input>
						<el-button type="primary" v-if="type == 2" @click="save">保存</el-button>
					</div>
				</div>
			</el-card>

			<div style="display: flex;">

				<el-card class="top15 flex_flex" style="height: calc(100vh - 215px);overflow-y: scroll">
					<div slot="header" class=" flex_hcneter_bet">
						<div>文件内容</div>
						<div class="flex_hcneter" v-if="type == 2">
							<div class="wordBreak">添加图片数量</div>
							<el-input class="margin_lr" v-model="num" placeholder="请输入添加图片数量"></el-input>
							<el-button type="primary" @click="addImage" >确定</el-button>
							<!-- <el-button @click="selectImage(1)" type="warning">导入文件</el-button> -->
							<input type="file" ref="fileInput" :multiple="multiple" @change="handleFileChange" style="display: none;" accept="image/*">
						</div>
					</div>
					<div class="img_block">
						<div v-for="(item,index) in imgList" :key="index">
							<div  :class="[selectImg.id === item.id ? 'select_bo' : '']" v-if="item.url"
							class="img_list flex_column" @click="imgClick(item,index)"  @dblclick="handleCommand('dakai', item,index)">
								<div class="flex_flex headers flex_zhcenter">
									<el-image
										style="width: 95%; height: 85%;border-radius: 6px;"
										:src="item.url"></el-image>
								</div>
								<div class="footers flex_hcneter_bet">
									<div class="flex_flex txt-ellipsis">{{index + 1}}</div>
									<el-dropdown @command="(command) => handleCommand(command, item,index)" class="margin_left" v-if="type == 2">
										<span class="el-dropdown-link">
											<i class="el-icon-more"></i>
										</span>
										<el-dropdown-menu slot="dropdown">
											<el-dropdown-item icon="el-icon-view" command="dakai">打开</el-dropdown-item>
											<el-dropdown-item icon="el-icon-edit" command="tihuan" >替换</el-dropdown-item>
											<el-dropdown-item icon="el-icon-delete" command="delImg">删除</el-dropdown-item>
										</el-dropdown-menu>
									</el-dropdown>
								</div>
							</div>
							<div class="add_block flex_zhcenter margin_right" style="margin-bottom: 15px;" v-else @click="selectImage(2,index)">
								<i class="el-icon-plus"></i>
							</div>
						</div>
						
						<div class="add_block flex_zhcenter" @click="tianjiaImg" v-if="type == 2">
							<i class="el-icon-plus"></i>
						</div>
					</div>
				</el-card>
					<div style="width: 30%;margin-top: 15px; margin-left: 15px;" class="right_yl">
							<el-card class="flex_column" style="height: calc(100vh - 215px);overflow-y: scroll;display: flex;flex-direction: column;">
								<div slot="header" class="clearfix">
										<span>公文预览</span>
								</div>
								<div class="flex_zhcenter flex_flex">
									<div style="width: 85%; height: 200px;border-radius: 6px;" id="ylImage">
										<el-image v-show="selectImg.url" 
										style="width: 100%; height: 100%;border-radius: 6px;" fit="contain"
										:src="selectImg.url"></el-image>
									</div>
								</div>
							</el-card>
					</div>
			</div>

			<!-- 添加或修改对话框 -->
			<el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
				<el-form ref="form" :model="form" :rules="rules" label-width="120px" id="screen">
					<el-form-item label="图片" prop="file">
						<imageUpload v-model="form.file" :limit="1"></imageUpload>
					</el-form-item>
					<el-form-item label="排序" prop="sort">
						<el-input-number v-model="form.sort" :step="1" :min="1"></el-input-number>
					</el-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button type="primary" @click="submitForm">确 定</el-button>
					<el-button @click="open = false">取 消</el-button>
				</div>
			</el-dialog>

			<div class="ylBlock flex_column" v-if="tpFlag">
				<div class="flex_hcneter flex_hend" style="margin-top:30px;margin-right:15px;">
					<div class="quanping" @click="toggleFullScreen">
						<i class="el-icon-full-screen margin_lr"></i>全屏
					</div>
					<div class="guanbi margin_left" @click="tpFlag = false">
						<i class="el-icon-close margin_lr"></i>关闭
					</div>
				</div>
				<div class="lunbo flex_zhcenter flex_flex">
					<div id="screen" class="flex_zhcenter" style="width: 100%;height:100%;">
						<div class="tuichu flex_zhcenter" @click="exitFullscreen" v-if="isScreen">
							<i class="el-icon-close"></i>
						</div>
						<el-carousel :height="isScreen ? '100vh' : '35rem'" ref="carouse"  style="width:100%;"  :autoplay="false" 
						:initial-index="lbIndex" :loop="false" arrow="always" trigger="click">
							<el-carousel-item v-for="(item,index) in ylImgList" :key="index" class="flex_zhcenter lunbo_item" >
								<div :id="'image'+index" :ref="'image'+index" class="lunbo_image shuiyin" v-if="tpFlag && type != 2"></div>
								<el-image :src="item.url" fit="contain" class="lunbo_image" @click="dinaji"></el-image>
							</el-carousel-item>
						</el-carousel>
					</div>
				</div>
				<div class="lunbo_num">
					{{lbIndex + 1}}/{{ylImgList.length}}
				</div>
			</div>
			<canvas ref="canvas" style="display:none"></canvas>
	</div>
</template>
<script>
import { getDocs,updateDocs,
	listDocsImg,delDocsImg,uploadDocimg } from "@/api/oa/trainDocument";
	// import watermark from 'watermarkjs';
	import watermark from 'watermark-dom'
export default {
	name: "detail",
	components: {},
	dicts: [],
	data() {
			return {
				id:'',
				num:'',//图片数量
				imgList:[],//图片列表
				selectImg:{},//选中的图片
				// 表单参数
				form: {},
				// 表单校验
				rules: {
					file: [{required: true, message: "图片不能为空", trigger: "change"}],
					sort: [{required: true, message: "排序不能为空", trigger: "blur"}],
				},
				// 弹出层标题
				title: "",
				// 是否显示弹出层
				open: false,
				info:{},//页面详情
				multiple:true,//是否多选
				lbIndex:0,//轮播下标
				tpFlag:false,
				uplodImg_type:2,//图片类型
				uplodImg_index:0,//图片下标
				ylImgList:[],//预览图片
				isScreen:false,//是否全
				fullscreen:false,
				watermarkedImage: '',
				syFlag:false,//是否显示水印
			}
	},
	created() {
		this.id = this.$route.query.id || ''
		this.type = this.$route.query.type || ''
		if(this.id) {
			this.getDocs()
			this.listDocsImg()
		}
		document.addEventListener('fullscreenchange', ()=> {
			if (!document.fullscreenElement) {
					console.log('退出全屏');
					this.isScreen = false
					this.syFlag = false
			} else {
					console.log('进入全屏');
			}
		});
		document.addEventListener("keydown", (event)=> {
			// 判断按下的键是否是回车键（键码为13）
			console.log(event)
			if(event.keyCode === 39) {//右键
				console.log("我点击了右键");
				if(this.lbIndex + 1 <= this.ylImgList.length - 1) {
					this.lbIndex = this.lbIndex + 1
					this.$refs.carouse.setActiveItem(this.lbIndex);
				}
			}
			if(event.keyCode === 37) {//左键
				console.log("我点击了左键");
				if(this.lbIndex > 0) {
					this.lbIndex = this.lbIndex - 1
					this.$refs.carouse.setActiveItem(this.lbIndex);
				}
			}
			if(event.keyCode === 27) {
				// 执行相应的操作，例如提交表单或执行搜索功能
				console.log("Enter key pressed!");
				this.tpFlag = false
				this.isScreen = false
				this.fullscreen = false
				this.syFlag = false
				// 在这里可以添加具体的逻辑代码
			}
		});
		
	},
	methods: {
		addWatermarks(text,index) {
      const watermarkDiv = this.$refs['image' + index][0];
			console.log('watermarkDiv',watermarkDiv)
      const canvas = document.createElement('canvas');
      canvas.width = this.info.wmWidth || 300;
      canvas.height = this.info.wmHeight || 300;
 
      const ctx = canvas.getContext('2d');
      ctx.rotate(-20 * Math.PI / 180);
      ctx.font = `${this.info.wmFontSize || 20}px Arial`;
      ctx.fillStyle = this.info.wmColor || `rgba(200, 200, 200, 0.50)`;//#818284
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillText(this.info.wmName || text, canvas.width / 2, canvas.height / 2);
      watermarkDiv.style.backgroundImage = `url(${canvas.toDataURL('image/png')})`;
      watermarkDiv.style.pointerEvents = 'none';
      watermarkDiv.style.position = 'absolute';
      watermarkDiv.style.top = 0;
      watermarkDiv.style.left = 0;
      watermarkDiv.style.width = '100%';
      watermarkDiv.style.height = '100%';
      watermarkDiv.style.zIndex = 9999;
    },
		dinaji(e){//点击
			console.log('e',e)
		},
		addWatermark() {
			return new Promise(resolve => {
        const image = document.querySelector('img');
				console.log('image',image)
				watermark([image])
					.image(watermark.text.lowerRight('Watermark', '20px Arial', '#ffffff', 0.5))
					.then((img) => {
						this.imageSrc = img.src;
						resolve(this.imageSrc)
						console.log('this.imageSrc',this.imageSrc)
					});
      })
      
    },
		exitFullscreen() {//点击退出全屏
			this.isScreen = false
			this.fullscreen = false
			this.syFlag = false
			if (document.exitFullscreen) {
				document.exitFullscreen();
			} else if (document.msExitFullscreen) {
				document.msExitFullscreen();
			} else if (document.mozCancelFullScreen) {
				document.mozCancelFullScreen();
			} else if (document.webkitExitFullscreen) {
				document.webkitExitFullscreen();
			}
		},
		// 全屏
		toggleFullScreen() {
			this.isScreen = true
			let element = document.getElementById('screen');
			try{
				this.fullscreen = false
				if (this.fullscreen) {
					if (document.exitFullscreen) {
					document.exitFullscreen();
					} else if (document.webkitCancelFullScreen) {
					document.webkitCancelFullScreen();
					} else if (document.mozCancelFullScreen) {
					document.mozCancelFullScreen();
					} else if (document.msExitFullscreen) {
					document.msExitFullscreen();
					}
				} else {
					if (element.requestFullscreen) {
					element.requestFullscreen();
					} else if (element.webkitRequestFullScreen) {
					element.webkitRequestFullScreen();
					} else if (element.mozRequestFullScreen) {
					element.mozRequestFullScreen();
					} else if (element.msRequestFullscreen) {
					// IE11
					element.msRequestFullscreen();
					}
				}
				this.fullscreen = !this.fullscreen;
			}catch{
				this.fullscreen = false
				this.toggleFullScreen()
			}
			this.syFlag = true
		},
		// 更多操作触发
    handleCommand(command, row,index) {
      this.form = {...row}
      switch (command) {
        case "delImg":
          this.delImg(row,index);
          break;
				case "tihuan":
					this.selectImage(2,index)
          break;
				case "dakai":
					this.ylImgList = this.imgList.filter(item=>item.url)
					this.lbIndex = index
					this.tpFlag = true
					if(this.type != 2) {
						this.$nextTick(()=>{
							this.ylImgList.map((item,index)=>{
								this.addWatermarks('万云科技',index)
							})
						})
					}
          break;
      }
    },
		handleAdd(index){//添加图片
			this.form = {docsId:this.id,sort:index + 1}
			this.open = true
			this.title = '添加图片'
		},
		async listDocsImg(){//培训文件图片
			let res = await listDocsImg({docsId:this.id})
			let data = res.data || []
			this.imgList = data.map(item=>{
				return {
					...item,
					// url:this.addWatermark(item.url),
				}
			})
		},
		delImg(row,index){//删除图片
			this.$modal.confirm(`确认要删除该数据吗？`).then(function() {
        return delDocsImg(row.id);
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        let imgList = [...this.imgList]
				imgList[index] = {}
				this.imgList = [...imgList]
      })
		},
		addImage(){//添加数量图片格子
			if( this.getStrNull(this.num) ) return this.$modal.msgError("图片数量不能为空");
			for(var i =0;i<this.num;i++ ){
				this.imgList.push({})
			}
			console.log('this.imgList',this.imgList)
		},
		tianjiaImg(){//添加图片
			this.imgList.push({})
		},
		async getDocs(){//培训文件详情
			let res = await getDocs(this.id)
			let data = res.data || {}
			this.info = data
		},
		selectImage(type,index) {//选择图片
			this.uplodImg_type = type
			this.uplodImg_index = index
			this.multiple = type == 1 ? true : false
			if(type == 2) {
				this.form = {
					docsId:this.id,sort:index + 1
				}
			}
			this.$nextTick(()=>{
				this.$refs.fileInput.click();
			})
		},
		handleFileChange(event) {
			console.log('handleFileChange',event)
			const file = event.target.files;
			
			// let list = file.filter(item=> item.type.startsWith('image/'))
			if(this.uplodImg_type == 2) {
				this.form.file = file[0]
				console.log('handleFileChange',file[0])
				let formDate = new FormData()
				formDate.append("docsId",this.id);
				formDate.append("sort",this.form.sort);
				formDate.append("file",file[0]);
				uploadDocimg(formDate).then(response => {
					this.$modal.msgSuccess("操作成功");
					let imgList = [...this.imgList]
					imgList[this.uplodImg_index] = response.data
					this.imgList = [...imgList]
				});
			}
		},
		shuiyin({id,text,color,fontSize,}){//水印图片
			this.$nextTick(()=>{
				const watermarkText = text || '万云科技'
				const options = {
					watermark_txt: watermarkText,
					watermark_color: color || 'gray',
					watermark_fontsize: fontSize || '14px',
					watermark_alpha: 0.5,
					watermark_angle: 15,
					watermark_width: 100,
					watermark_height: 20,
					watermark_parent_node: id,
				}
				watermark.load(options)
			})
		},
		imgClick(e){//图片点击 ylImage
			this.selectImg = e
			// this.shuiyin('ylImage')
			// this.$nextTick(()=>{
			// 	const watermarkText = '万云科技'
			// 	const options = {
			// 		watermark_txt: watermarkText,
			// 		watermark_color: 'gray',
			// 		watermark_fontsize: '14px',
			// 		watermark_alpha: 0.5,
			// 		watermark_angle: 15,
			// 		watermark_width: 100,
			// 		watermark_height: 20,
			// 		watermark_parent_node: 'ylImage',
			// 	}
			// 	watermark.load(options)
			// })
		},
		getStrNull(str){//判断是否为空
      return str === '' || str === null || str === undefined
    },
		save(){//保存
			if( this.getStrNull(this.info.name) ) return this.$modal.msgError("文件名称不能为空");
			updateDocs(this.info).then(response => {
				this.$modal.msgSuccess("保存成功");
				this.getDocs();
			});
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs["form"].validate(valid => {
				if (valid) {
					uploadDocimg(this.form).then(response => {
						this.$modal.msgSuccess("操作成功");
						this.open = false;
						this.getList();
					});
				}
			});
		},
		// 上传失败
    handleUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
	}

}
</script>
<style>
/deep/ #ylImage #wm_div_id div{
	z-index: 1500!important;
}
</style>
<style lang="scss">
.ylBlock{
	width: 100%;height: 100%;position: fixed;top: 0;left: 0;
	z-index: 2005;background-color: black;
	.quanping{color: #fff;cursor: pointer;}
	.guanbi{color: #fff;cursor: pointer;}
	.lunbo{
		width: 100%;margin-top: 30px;overflow: hidden;
	}
	// .lunbo_item{position: relative;}
	.shuiyin{position: fixed;left: 0;top: 0;z-index: 10;}
	.tuichu{
		color: #fff;font-size: 24px;cursor: pointer;
		position: absolute;top: 45px;width: 50px;height: 50px;
		background-color: #203349;border-radius: 50%;z-index: 100;
	}
	.lunbo_num{color: #fff;margin-bottom: 30px;text-align: center;}
	.lunbo_image{
		width: 100%;height: 100%;
	}
	.el-carousel__container{}
}
.add_block{
	background-color: #E3E3E3;border-radius: 6px;border: 1px solid #E3E3E3;
	height: 108px;width: 121px;cursor: pointer;font-size: 25px;font-weight: bold;
}
.img_block{display: flex;flex-wrap: wrap;}
.img_list{
	width: 121px;border: 1px solid #F5F5F5;border-radius: 6px;overflow: hidden;
	height: 108px;margin-right: 15px;margin-bottom: 15px;cursor: pointer;
	.headers{
		background-color: #E3E3E3;width: 100%;overflow: hidden;
	}
	.footers{
		height: 21px;color: #8093AF;font-size: 12px;
		padding: 0 5px;
	}
}
.select_bo{border: 1px solid #11A983;}
.right_yl{
	.el-card__body{
		flex: 1;display: flex;flex-direction: column;
	}
}
.margin_left{margin-left: 10px;}
.margin_right{margin-right: 10px;}
.margin_lr{margin: 0 10px;}
</style>